import React, { CSSProperties } from 'react'
import { Face } from '@material-ui/icons'
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle,Button, TextField } from '@material-ui/core'
import {inject,observer} from 'mobx-react'
import UserStore from '../../../store/modules/userStore'
import Message from '../../../components/Message/Message'
import { CgAns,chAva } from '../../../api/user'

const ChangeAvatarStyle: CSSProperties = {
    backgroundColor: '#fff',
    boxShadow: '1px 2px 25px 0px rgb(0 0 0 / 10%)',
    borderRadius: '15px',
    margin: '2vh 4vw',
    padding: '1.5vh 3vw',
    display: 'flex',
    alignItems: 'center'
}
interface IProps {
    userStore?: UserStore
}
const ChangeAvatar = (props: IProps) => {
    const [open,setOpen] = React.useState<boolean>(false)
    const [avatar,setAvatar] = React.useState<any>('')
    const handleUpdate = () => {
        const formData = new FormData()
        if(avatar){
            formData.append('uploadFile',avatar)
            chAva(formData)
                .then(res => {
                    const {msg,code} = res as unknown as CgAns
                    if(code === 200){
                        props.userStore?.getUserInfo()
                        Message('success',msg)
                        setOpen(false)
                    }else{
                        Message('error',msg)
                    }
                    setAvatar('')
                })
                .catch(err => {
                    console.log(err);
                })
        }else{
            Message('error','请选择图片后再上传')
        }
    }
    return (
        <>
            <div style={ChangeAvatarStyle} onClick={() => {setOpen(true)}}>
                <Face />
                <span style={{ marginLeft: '4vw', fontSize: '13px' }}>修改头像</span>
            </div>
            <Dialog open={open}>
                <DialogTitle>修改头像</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        请在设备中选择要更换的头像
                    </DialogContentText>
                    <TextField  type="file" fullWidth  onChange={(e) => {setAvatar((e.target as any).files[0])}} color="secondary" variant="outlined" style={{marginTop: '1vh'}} />
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleUpdate} color='secondary'>更改</Button>
                    <Button onClick={() => {setOpen(false)}} color='secondary'>取消</Button>
                </DialogActions>
            </Dialog>
        </>
    )
}

export default inject('userStore')(observer(ChangeAvatar))